package DCSource;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;

public class networker{
	private boolean isWindowsSystem()
	  { String osName = System.getProperty("os.name").toLowerCase();
	    return osName.indexOf("windows") >= 0;
	  }
	  
	private boolean isLinuxSystem()
	  { String osName = System.getProperty("os.name").toLowerCase();
	    return osName.indexOf("linux") >= 0;
	  }
	private String umsch(){
		if (isWindowsSystem()==true){
			return String.valueOf((char)13)+String.valueOf((char)10);
		}else{return String.valueOf((char)10);}
	}
	public networker(){}
	public boolean ping(String IP,String Port){
		try {
			InetAddress host = InetAddress.getByName(IP);
			int         port = Integer.parseInt(Port);
			Socket so = new Socket(host,port);
		    so.close();
		    return true;
		} catch (UnknownHostException e) {
			return false;
		} catch (IOException e) {
			return false;
		}
	}
	public void Download(String url,String downloadurl){
		try{
		  final URL Url = new URL(downloadurl);
		  final URLConnection conn = Url.openConnection();
		  final InputStream is = new BufferedInputStream(conn.getInputStream());
		  final OutputStream os =
		  new BufferedOutputStream(new FileOutputStream(url));
		  byte[] chunk = new byte[1024];
		  int chunkSize;
		  while ((chunkSize = is.read(chunk)) != -1) {
		    os.write(chunk, 0, chunkSize);
		  }
		  os.flush(); // Necessary for Java < 6
		  os.close();
		  is.close();}catch(Exception e){}
		}
	public String httpDownload(String url){
		HttpURLConnection connection = null;
		try
	    {
	      String link = url;
	      String Page="";
	      URL serverAddress = new URL(url);
        connection = (HttpURLConnection)serverAddress.openConnection();
        connection.setDoOutput(true);
        connection.setReadTimeout(30000);
	      BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
	      String line;
	      while ((line = br.readLine()) != null) {
	    	  if (Page.equals("")){
	    		  Page+=line;}else{
	    			  Page+=umsch()+line;
	    		  }
	      }
	      connection.disconnect();
	      return Page;
	    } catch (Exception exp) {return exp.getMessage();}
	}
}
